﻿using MongoDB.Driver;
using System;

namespace GT.Framework.Mongo.Core
{
    public class MongoManager
    {
        /// <summary>
        /// redis配置文件信息
        /// </summary>
        private static MongoConfig MongoConfig = MongoConfig.GetConfig();

        private static IMongoDatabase db;

        /// <summary>
        /// 静态构造方法，初始化链接池管理对象
        /// </summary>
        static MongoManager()
        {
            CreateManager();
        }

        /// <summary>
        /// 创建链接池管理对象
        /// </summary>
        private static void CreateManager()
        {
            //获取mongodb指定数据库
            //var setting = new MongoClientSettings {
            //    Server = new MongoServerAddress(MongoConfig.ServerConStr, MongoConfig.Port),
            //    MaxConnectionPoolSize = MongoConfig.MaxConnectionPoolSize,
            //    MaxConnectionIdleTime = TimeSpan.FromSeconds(MongoConfig.MaxConnectionIdleTime),
            //    MaxConnectionLifeTime = TimeSpan.FromSeconds(MongoConfig.MaxConnectionLifeTime),
            //    ConnectTimeout = TimeSpan.FromSeconds(MongoConfig.ConnectTimeout),
            //    WaitQueueSize = MongoConfig.WaitQueueSize,
            //    SocketTimeout = TimeSpan.FromSeconds(MongoConfig.SocketTimeout),
            //    WaitQueueTimeout = TimeSpan.FromSeconds(MongoConfig.WaitQueueTimeout)
            //};
            //var mongoClient = new MongoClient(setting);
            var client = new MongoClient(MongoConfig.ServerConStr);

            db = client.GetDatabase(MongoConfig.DefaultDb);
        }

        private static void IsDbNull()
        {
            if (db != null)
                return;
            throw new Exception("the mongodb is null,plese set it on method SetMongoDatabase");
        }

        /// <summary>
        /// 客户端缓存操作对象
        /// </summary>
        public static IMongoDatabase GetClient()
        {
            if (db == null)
                CreateManager();
            return db;
        }

        /// <summary>
        /// 获取数据库中的集合(相当于表)
        /// </summary>
        public static IMongoCollection<TEntity> GetMongoCollection<TEntity>(string name)
        {
            IsDbNull();//检测数据库是否存在
            return db.GetCollection<TEntity>(name);
        }

        /// <summary>
        /// 删除集合
        /// </summary>
        /// <param name="name">集合名称</param>
        public static void DropCollection(string name)
        {
            db.DropCollection(name);
        }

    }
}
